/**
 * Aorey Toy(mini)
 *
 * 因为我认为mybatis的开发模式有问题,并且方便以后和spring的团队配合,所以将Aorey Toy 的部分代码
 * 提取,做成一个微框架,微框架只是针对数据处理部分，目标是快速处理数据,替代mybatis
 * 
 * mybatis是优秀的，但是我个人真的不太习惯ORM这种方式
 *
 * @author 迟胜强
 * @date 2018-09-03
 */
package aorey.framework.web;

import aorey.config.FrameworkConfig;
import aorey.database.DataCheck;
import aorey.database.DataSourceConfig;
import aorey.nosql.EhcacheUtil;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;

import org.dom4j.DocumentException;

public class FrameworkFilter implements Filter {
    
    private String webRoot ;
    private EhcacheUtil framework;
    private HashMap<String, DataSource> dataBaseDrivers;
    private Server server;
    
    @Override
    public void init(FilterConfig filterConfig)  {
//        this.webRoot = filterConfig.getServletContext().getRealPath("/")+filterConfig.getInitParameter("config");
    	this.server = new Server();
    	// 网站根目录
    	this.webRoot = filterConfig.getServletContext().getRealPath("/");
    	this.server.webRoot = this.webRoot;
    	// 加载Ehcache配置文件
    	this.framework = new EhcacheUtil(this.webRoot+FrameworkConfig.ehcacheConfig);
    	this.server.framework = this.framework;
    	// 加载数据源配置文件
    	dataBaseDrivers = new DataSourceConfig().read(this.webRoot+FrameworkConfig.dataBaseConfig);
    	// 初始化数据校验文件配置,实例化存入Ehcache
    	DataCheck dataCheck = new DataCheck();
    	try {
			dataCheck.getDataType(this.webRoot+FrameworkConfig.dataTypeConfig);
			this.server.dataCheck = dataCheck;
			this.framework.put("config", "datatype", dataCheck);
		} catch (DocumentException e) {
			
//			e.printStackTrace();
			System.out.println("[ATM] Error:"+e.getMessage());
		}
    	
    	
    	
    	
    	this.framework.put("database", "drivers", dataBaseDrivers);
    	this.server.dataBaseDrivers = dataBaseDrivers;
    	filterConfig.getServletContext().setAttribute("aorey", this.framework);
    	
        System.out.println("    ___                            ______           \n" + 
        		"   /   | ____  ________  __  __   /_  __/___  __  __\n" + 
        		"  / /| |/ __ \\/ ___/ _ \\/ / / /    / / / __ \\/ / / /\n" + 
        		" / ___ / /_/ / /  /  __/ /_/ /    / / / /_/ / /_/ / \n" + 
        		"/_/  |_\\____/_/   \\___/\\__, /    /_/  \\____/\\__, /  \n" + 
        		"                      /____/               /____/  [mini]\n" + 
        		"\n" + 
        		"");

    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
    }
    
    @Override
    public void destroy() {
    	System.out.println("Aorey Toy [mini] Stop......");
        this.framework.close();
    }
    
}
